package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.dao.DeviceRepository;
import edu.ynu.se.xiecheng.achitectureclass.dao.GreenhouseRepository;
import edu.ynu.se.xiecheng.achitectureclass.dao.UserRepository;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import edu.ynu.se.xiecheng.achitectureclass.entity.Greenhouse;
import edu.ynu.se.xiecheng.achitectureclass.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Set;

/**
 * 数据初始化服务
 * 负责在系统启动时初始化必要的基础数据
 * 包括创建默认大棚和设备数据
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DataInitializationService implements CommandLineRunner {

    private final GreenhouseRepository greenhouseRepository;
    private final DeviceRepository deviceRepository;
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    /**
     * 系统启动时执行的初始化方法
     * 检查是否需要创建默认数据，如果需要则创建默认大棚和设备
     *
     * @param args 启动参数
     */
    @Override
    @Transactional
    public void run(String... args) {
        log.info("开始初始化数据...");
        initializeUsers();
        initializeGreenhouse();
        log.info("数据初始化完成.");
    }

    private void initializeUsers() {
        if (userRepository.count() == 0) {
            log.info("初始化用户数据...");
            // 创建管理员用户
            User admin = new User();
            admin.setUsername("admin");
            admin.setPassword(passwordEncoder.encode("admin123"));
            admin.setName("系统管理员");
            admin.setRoles(Set.of("ADMIN"));
            admin.setCreateTime(new Date());
            admin.setEnabled(true);
            userRepository.save(admin);
            log.info("创建管理员用户: {}", admin.getUsername());

            // 创建普通用户
            User user = new User();
            user.setUsername("user");
            user.setPassword(passwordEncoder.encode("user123"));
            user.setName("测试用户");
            user.setRoles(Set.of("USER"));
            user.setCreateTime(new Date());
            user.setEnabled(true);
            userRepository.save(user);
            log.info("创建普通用户: {}", user.getUsername());
        }
    }

    /**
     * 初始化大棚数据
     * 如果数据库中没有大棚数据，则创建默认大棚和设备
     */
    private void initializeGreenhouse() {
        log.info("检查大棚数据...");
        Greenhouse greenhouse;
        if (greenhouseRepository.count() == 0) {
            greenhouse = new Greenhouse();
            greenhouse.setName("智能温室1号");
            greenhouse.setAddress("云南大学软件学院");
            greenhouse.setArea(100.0);
            greenhouse.setCreateTime(new Date());
            greenhouse = greenhouseRepository.save(greenhouse);
            log.info("创建大棚: {}", greenhouse.getName());

            initializeDevices(greenhouse);
        } else {
            log.info("大棚数据已存在，跳过初始化");
        }
    }

    private void initializeDevices(Greenhouse greenhouse) {
        log.info("检查设备数据...");
        if (deviceRepository.count() == 0) {
            log.info("开始初始化设备...");
            
            Device device1 = new Device();
            device1.setName("土壤温度传感器");
            device1.setDeviceType("SOIL_SENSOR");
            device1.setSerialNumber("327061586065758015");
            device1.setUnit("℃");
            device1.setBoxNo("300822040454");
            device1.setGreenhouse(greenhouse);
            device1.setCreateTime(new Date());
            deviceRepository.save(device1);
            log.info("创建设备: {}", device1.getName());

            Device device2 = new Device();
            device2.setName("土壤PH传感器");
            device2.setDeviceType("SOIL_SENSOR");
            device2.setSerialNumber("327061586065758007");
            device2.setUnit("pH");
            device2.setBoxNo("300822040454");
            device2.setGreenhouse(greenhouse);
            device2.setCreateTime(new Date());
            deviceRepository.save(device2);
            log.info("创建设备: {}", device2.getName());

            Device device3 = new Device();
            device3.setName("土壤磷含量传感器");
            device3.setDeviceType("SOIL_SENSOR");
            device3.setSerialNumber("327061586065758009");
            device3.setUnit("mg/kg");
            device3.setBoxNo("300822040454");
            device3.setGreenhouse(greenhouse);
            device3.setCreateTime(new Date());
            deviceRepository.save(device3);
            log.info("创建设备: {}", device3.getName());

            Device device4 = new Device();
            device4.setName("土壤钾含量传感器");
            device4.setDeviceType("SOIL_SENSOR");
            device4.setSerialNumber("327061586065758010");
            device4.setUnit("mg/kg");
            device4.setBoxNo("300822040454");
            device4.setGreenhouse(greenhouse);
            device4.setCreateTime(new Date());
            deviceRepository.save(device4);
            log.info("创建设备: {}", device4.getName());

            Device device5 = new Device();
            device5.setName("光照度传感器");
            device5.setDeviceType("SOIL_SENSOR");
            device5.setSerialNumber("327061586065758012");
            device5.setUnit("Lux");
            device5.setBoxNo("300822040454");
            device5.setGreenhouse(greenhouse);
            device5.setCreateTime(new Date());
            deviceRepository.save(device5);
            log.info("创建设备: {}", device5.getName());

            Device device6 = new Device();
            device6.setName("摄像头");
            device6.setDeviceType("CAMERA");
            device6.setSerialNumber("L29334649");
            device6.setBoxNo(null);
            device6.setGreenhouse(greenhouse);
            device6.setCreateTime(new Date());
            deviceRepository.save(device6);
            log.info("创建设备: {}", device6.getName());
            
            log.info("设备初始化完成");
        } else {
            log.info("设备数据已存在，跳过初始化");
        }
    }
} 